package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.dto.CommissionItemDTO;
import info.batcloud.fanli.core.domain.MaterialConfig;
import info.batcloud.fanli.core.entity.Material;
import info.batcloud.fanli.core.enums.MaterialStatus;
import info.batcloud.fanli.core.repository.MaterialRepository;
import info.batcloud.fanli.core.service.CommissionItemService;
import info.batcloud.fanli.core.service.MaterialService;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.Date;
import java.util.List;

@Service
public class MaterialServiceImpl implements MaterialService {

    @Inject
    private MaterialRepository materialRepository;

    @Inject
    private CommissionItemService commissionItemService;

    @Override
    public void createMaterial(MaterialCreateParam param) {
        Material material = new Material();
        material.setName(param.getName());
        material.setConfigJson(param.getConfigJson());
        material.setStatus(param.getStatus());
        material.setCreateTime(new Date());
        materialRepository.save(material);
    }

    @Override
    public void updateMaterial(long id, MaterialUpdateParam param) {
        Material material = materialRepository.findOne(id);
        material.setName(param.getName());
        material.setConfigJson(param.getConfigJson());
        material.setStatus(param.getStatus());
        material.setUpdateTime(new Date());
        materialRepository.save(material);
    }

    @Override
    public void setStatus(long id, MaterialStatus status) {
        Material material = materialRepository.findOne(id);
        material.setStatus(status);
        materialRepository.save(material);
    }

    @Override
    public List<Material> findAll() {
        return materialRepository.findByStatusNotOrderByIdDesc(MaterialStatus.DELETED);
    }

    @Override
    public List<Material> findByStatus(MaterialStatus status) {
        return materialRepository.findByStatusOrderByIdDesc(status);
    }

    @Override
    public Material findById(long id) {
        return materialRepository.findOne(id);
    }

    @Override
    public boolean checkCommissionItemInMaterial(long materialId, long commissionItemId) {
        Material material = materialRepository.findOne(materialId);
        MaterialConfig config = material.getConfig();
        CommissionItemDTO ci = commissionItemService.findById(commissionItemId);
        /**
         * 在这里只验证售价以及佣金，其他属性暂不验证 TODO
         * */
        if (config.getEndPrice() != null && config.getEndPrice().floatValue() < ci.getPrice()) {
            return false;
        }
        if (config.getMinCommissionFee() != null
                && config.getMinCommissionFee().floatValue() > ci.getFullCommission()) {
            return false;
        }
        return true;
    }

}
